#include <stdbool.h>
#include <stdlib.h>
#include "drv_led.h"
#include "dev_common.h"
#include "dev_pin.h"

typedef struct Dev_BoardLed_t Dev_BoardLed;
struct Dev_BoardLed_t {
    Led base;
    PhyPin pin;
};

errno_t Dev_BoardLedSetStatus(Led *pthis, bool state)
{
    Dev_BoardLed *me = (Dev_BoardLed *)pthis;
    SetPinStatus(&me->pin, !state);
    return STATE_OK;
}

errno_t Dev_BoardLedGetStatus(Led *pthis, bool *state)
{
    Dev_BoardLed *me = (Dev_BoardLed *)pthis;
    *state = !GetPinStatus(&me->pin);
    return STATE_OK;
}

errno_t Dev_BoardLedSwitch(Led *pthis)
{
    Dev_BoardLed *me = (Dev_BoardLed *)pthis;
    bool state;
    pthis->getStatus(pthis, &state);
    state = !state;
    pthis->setStatus(pthis, state);
    return STATE_OK;
}

void DeleteBoardLed(Led *pthis)
{
    if (pthis == NULL) {
        return;
    }
    free(pthis);
}

Led *Dev_BoardLedCtor(void)
{
    Dev_BoardLed *me = (Dev_BoardLed *)malloc(sizeof(Dev_BoardLed));
    me->pin.gpio = GPIOC;
    me->pin.pinId = GPIO_PIN_13;
    me->base.getStatus = Dev_BoardLedGetStatus;
    me->base.setStatus = Dev_BoardLedSetStatus;
    me->base.switchLed = Dev_BoardLedSwitch;
    me->base.remove = DeleteBoardLed;

    EnableDevCLK(me->pin.gpio);

    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStructure.Pin = GPIO_PIN_13;
    GPIO_InitStructure.Pull = GPIO_PULLUP;
    GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_MEDIUM;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStructure);
    
    return (Led *)me;
}

void Dev_BoardLedInit(void)
{
    Led *led = Dev_BoardLedCtor();
    led->setStatus(led, false);
    SetBoardLed(led);
}
